﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using GhostscriptSharp;
using System.Web;
using System.Drawing;

// Download Ghostscript and install http://downloads.ghostscript.com/public/gs905w64.exe 
namespace SPThumbnailExtender.Interne
{
    internal class ThumbnailPDF : ThumbnailBase, IDisposable
    {
        public ThumbnailPDF(Uri FileURI)
            : base(FileURI)
        {

        }

        public ThumbnailPDF(Uri FileURI, int Width, int Height)
            : base(FileURI, Width, Height)
        {

        }

        public override System.Drawing.Bitmap GenerateThumbnail()
        {
            return GenerateThumbnail(1);
        }

        public override System.Drawing.Bitmap GenerateThumbnail(int Page)
        {
            string strPathPNG = Helper.GetSourceFilename(this.FileUri.AbsoluteUri, Width, Height, 0, ".png");
            FileInfo file = new FileInfo(strPathPNG);
            if (!file.Directory.Exists)
                file.Directory.Create();
            string strPathPDF = Helper.GetSourceFilename(this.FileUri.AbsoluteUri, Width, Height, 0, ".pdf");


            byte[] byteFile = Helper.ReadToEnd(this.GetFileStream());
            File.WriteAllBytes(strPathPDF, byteFile);
            GhostscriptSettings s = new GhostscriptSettings();
            s.Device = GhostscriptSharp.Settings.GhostscriptDevices.png16m;
            string strPage = (Page + 1).ToString();
            s.Page.Start = int.Parse(strPage);
            s.Page.End = int.Parse(strPage);

            s.Resolution = new System.Drawing.Size(Width, Height);


            GhostscriptSharp.Settings.GhostscriptPageSize pageSize = new GhostscriptSharp.Settings.GhostscriptPageSize();
            pageSize.Manual = s.Resolution;
            s.Size = pageSize;
            GhostscriptSharp.GhostscriptWrapper.GenerateOutput(strPathPDF, strPathPNG, s);
            File.Delete(strPathPDF);
            Bitmap cachedFile = new Bitmap(strPathPNG);
            Helper.DeleteThumbnail(this.FileUri, Page);
            Helper.InsertThumbnail(this.FileUri, Page, cachedFile);

            File.Delete(strPathPNG);
            return cachedFile;
        }

        public override int GetCount()
        {
            using (Stream str = this.GetFileStream())
            {
                StreamReader sr = new StreamReader(str);

                string pdf = sr.ReadToEnd();
                Regex rx = new Regex(@"/Type\s*/Page[^s]");
                MatchCollection match = rx.Matches(pdf);

                string PgCount = match.Count.ToString();
                int iReturn;
                return int.TryParse(PgCount, out iReturn) ? iReturn : 0;
            }

        }

        public void Dispose()
        {
            
        }

        public override void GenerateThumbnails()
        {
            string strPathPNG = Helper.GetSourceFilename(this.FileUri.AbsoluteUri, Width, Height, -1, ".png");
            int startToFind = strPathPNG.LastIndexOf("\\") + 1;
            int LenghtToFind = (strPathPNG.LastIndexOf("%d")) - startToFind;
            string strPatternToFind = strPathPNG.Substring(startToFind, LenghtToFind);
            string strPatternToPageFindStart = strPathPNG.Substring(0, strPathPNG.LastIndexOf("%d"));
            string strPatternToPageFindEnd = strPathPNG.Substring(strPathPNG.LastIndexOf("%d") + 2);
            FileInfo file = new FileInfo(strPathPNG);
            if (!file.Directory.Exists)
                file.Directory.Create();
            string strPathPDF = Helper.GetSourceFilename(this.FileUri.AbsoluteUri, Width, Height, 0, ".pdf");


            byte[] byteFile = Helper.ReadToEnd(this.GetFileStream());
            File.WriteAllBytes(strPathPDF, byteFile);
            GhostscriptSettings s = new GhostscriptSettings();
            s.Device = GhostscriptSharp.Settings.GhostscriptDevices.png16m;
            object o = Helper.GetParameter("SPThumbnailExtender.NbPage");
            
            if(o==null || int.Parse(o.ToString())==-1)
            {
                s.Page.AllPages = true;                
            }
            else
            {
                s.Page.Start = 1;
                s.Page.End = int.Parse(o.ToString());
            }
            s.Resolution = new System.Drawing.Size(60, 85);


            GhostscriptSharp.Settings.GhostscriptPageSize pageSize = new GhostscriptSharp.Settings.GhostscriptPageSize();
            pageSize.Manual = s.Resolution;
            s.Size = pageSize;
            GhostscriptSharp.GhostscriptWrapper.GenerateOutput(strPathPDF, strPathPNG, s);
            File.Delete(strPathPDF);
            string strDirectory = Path.GetDirectoryName(strPathPNG);
            

            string[] strPathArray= Directory.GetFiles(strDirectory, strPatternToFind + "*.png");
            Helper.DeleteThumbnailsForDocument(this.FileUri);
            foreach (string str in strPathArray)
            {
                string strPage = str.Replace(strPatternToPageFindStart, "").Replace(strPatternToPageFindEnd, "");
                int iPage = int.Parse(strPage)-1;
                using (Bitmap bmp=(Bitmap) Bitmap.FromFile(str))
                {
                    Helper.InsertThumbnail(this.FileUri, iPage, bmp);
                }
                File.Delete(str);
            }

        }
    }
}
